/**
 * 
 */
package org.jinion.test.dao;

import java.sql.SQLException;
import java.util.Map;

import org.jinion.database.AbstractDatabase;
import org.jinion.database.DatabaseFactory;
import org.jinion.database.model.AbstractResult;
import org.jinion.test.model.User;
import org.jinion.util.BeanMap;

/**
 * @author zhlmmc
 *
 */
public class UserDAO {
	private AbstractDatabase myDatabase;
	
	public UserDAO() throws DAOException{
		try {
			myDatabase = DatabaseFactory.getDatabase();
		} catch (Exception e) {
			throw new DAOException(e);
		} 
	}
	
	public User getUser(int userId) throws DAOException{
		myDatabase.where("userId", userId);
		
		try {
			AbstractResult result = myDatabase.query("user");
			if (result.size() > 0) {
				User user = new User();
				BeanMap map = new BeanMap(result.getTable().getRow(1).getMap());
				map.fillBean(user);
				
				return user;
			}
		} catch (SQLException e) {
			throw new DAOException(e);
		}
		
		return null;
	}
	
	public User findUser(String email, String password) throws DAOException{
		myDatabase.where("email", email);
		myDatabase.where("password", password);
		
		try {
			AbstractResult result = myDatabase.query("user");
			if (result.size() > 0) {
				User user = new User();
				BeanMap map = new BeanMap(result.getTable().getRow(1).getMap());
				map.fillBean(user);
				
				return user;
			}
		} catch (SQLException e) {
			throw new DAOException(e);
		}
		
		return null;
	}
	
	public void createUser(User user) throws DAOException{
		Map map = new BeanMap(user);
		try {
			AbstractResult result = myDatabase.insert("user", map);
			Object obj = result.getFirstGeneratedKey();
			if (obj != null) {
				user.setUserId((Integer)obj);
			}
			else{
				throw new DAOException("Can not get generated primary key.");
			}
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	
	public void updateUser(User user) throws DAOException{
		myDatabase.where("userId", user.getUserId());
		Map map = new BeanMap(user);
		try {
			myDatabase.update("user", map);
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	
	public void deleteUser(User user) throws DAOException{
		myDatabase.where("userId", user.getUserId());
		try {
			myDatabase.delete("user");
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	
	/**
	 * Just for test convenient.
	 */
	public void deleteAll() throws DAOException{
		try {
			myDatabase.delete("user");
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
}
